<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议 https://mit-license.org
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------
namespace app\api\middleware;

use app\admin\model\Platform;
use app\common\service\AuthService;
use Firebase\JWT\JWT;
use think\Request;
use app\admin\model\SystemOperationRecord;

/**
 * 检测用户登录和节点权限
 * Class CheckAdmin
 *
 * @package app\api\middleware
 */
class CheckAdmin
{
    
    use \app\common\traits\JumpTrait;

    public function handle(Request $request, \Closure $next)
    {
        $adminConfig = config('admin');
        $controller = $request->controller();
        $action = $request->action();
        // 验证登录
        if (! in_array($controller, $adminConfig['no_login_controller']) && ! in_array($action, $adminConfig['no_login_node'])) {
            // 验证token
            $header = $request->header();
            if (empty($header['authorization'])) {
                return msg($header, 401, "你还未登录 请进行登录!");
            }
            $authorization = $header['authorization'];
            $key = config('app.token_key');
            try {
                $keys = new \Firebase\JWT\Key($key, 'HS256');
                $data = JWT::decode($authorization, $keys);
                $uid = $data->data->uid;
                $request->user_id = $uid;

                $user = \app\admin\model\SystemUser::where("user_id", $uid)->find();
                if (empty($user)) {
                    return msg([], 401, "用户不存在!");
                }


                $request->_USER = $user;
                $request->tenant_id = $user['tenant_id'];
                $request->platform_id = $user['platform_id'];
                if ($user['platform_id'] > 0){
                    $platformModel  = new Platform();
                    $platformInfo = $platformModel->where(['id' =>$user['platform_id']])->find();
                    if ( $platformInfo['expiration_time'] < time()){
                        session('admin', null);
                        $this->success('平台已过期');
                        return ;
                    }

                }

                $operation = [
                    'user_id' => $request->user_id,
                    'module' => $request->controller(),
                    'url' => $request->url(),
                    'request_method' => $request->method(),
                    'method' => $request->action(),
                    'params' => json_encode($request->param()),
                    'os' => get_os(),
                    'device' => get_device(),
                    'browser' => get_broswer(),
                    'ip' => $request->ip(),
                    'status' => $_SERVER['REDIRECT_STATUS'] == '200' ? 0 : 1,
                    'tenant_id' => $user['tenant_id'],
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'update_time' => date('Y-m-d H:i:s', time())
                ];
                $operationRecord = new SystemOperationRecord();
                $operationRecord->save($operation);
            } catch (\Exception $e) {
                return msg([], 401, '未登录或登陆已失效，请重新登陆' . $e->getMessage());
            }
        }
        
        return $next($request);
    }
}